package com.example.gkcircle.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVACL;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.CountCallback;
import com.avos.avoscloud.SaveCallback;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bm.library.PhotoView;
import com.example.gkcircle.App;
import com.example.gkcircle.R;
import com.example.gkcircle.activity.LoginActivity;
import com.example.gkcircle.activity.PhotoViewAcitivty;
import com.example.gkcircle.bean.Lost;
import com.example.gkcircle.bean.Wish;
import com.example.gkcircle.db.DBUtil;
import com.example.gkcircle.fragment.lost.LostFragment;
import com.example.gkcircle.utils.ActivityUtil;
import com.example.gkcircle.utils.CommonUtil;
import com.example.gkcircle.utils.MyAlertView;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.ToastFactory;
import com.example.gkcircle.utils.UniversalImageLoader;

import java.util.List;

/**
 * 失物
 * Created by Jehu on 16/3/19.
 */
public class WishAdapter extends BaseAdapter{


    private List<Wish> mData;
    private Activity mActivity;
    private LayoutInflater inflater;

    public WishAdapter(Activity activity, List<Wish> data) {
        this.mData=data;
        this.mActivity = activity;
        this.inflater = LayoutInflater.from(mActivity);
    }

    @Override
    public int getCount() {
        return mData==null?0:mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    static class ViewHolder{
        ImageView avatar;
        TextView username;
        TextView date;
        TextView content;
        PhotoView photoView;
        ImageButton wishBtn;
        LinearLayout wishLayout;
        TextView wishCount;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if(convertView==null){
            viewHolder=new ViewHolder();
            convertView=inflater.inflate(R.layout.home_list_item,null);
            viewHolder.avatar=(ImageView)convertView.findViewById(R.id.home_list_item_avatar);
            viewHolder.username=(TextView)convertView.findViewById(R.id.home_list_item_username);
            viewHolder.date=(TextView)convertView.findViewById(R.id.home_list_item_date);
            viewHolder.content=(TextView)convertView.findViewById(R.id.home_list_item_content);
            viewHolder.photoView=(PhotoView)convertView.findViewById(R.id.home_list_item_photo);
            viewHolder.wishBtn=(ImageButton)convertView.findViewById(R.id.home_list_item_wish_btn);
            viewHolder.wishLayout=(LinearLayout)convertView.findViewById(R.id.home_list_item_wish_layout);
            viewHolder.wishCount=(TextView)convertView.findViewById(R.id.home_list_item_wish_count);
            convertView.setTag(viewHolder);
        }else{
            viewHolder=(ViewHolder)convertView.getTag();
        }
        final Wish wish=mData.get(position);
        final AVUser user=wish.getUser();
        viewHolder.content.setText(wish.getContent());

        viewHolder.username.setText(user.get("nickname").toString());
        viewHolder.content.setText(wish.getContent());
        viewHolder.date.setText(wish.getCreatedAt());
        viewHolder.wishCount.setText(wish.getLikeCount()+"");
        //用户头像
        if(null!=user.getAVFile("avatar")){
            int width=mActivity.getResources().getDimensionPixelSize(R.dimen.love_avatar_width);
            //获取缩略图url
            String avatarUrl=user.getAVFile("avatar").getThumbnailUrl(true,width,width);
            UniversalImageLoader.getIntance().displayImage(avatarUrl,viewHolder.avatar,UniversalImageLoader.getAvatarOptions(),UniversalImageLoader.getAnimateFirstDisplayListener());
        }else{
            viewHolder.avatar.setImageResource(R.mipmap.personal_default_user_icon);
        }

        //用户是否点赞过
        if(wish.isLike()){
            viewHolder.wishBtn.setBackground(mActivity.getResources().getDrawable(R.mipmap.wish_pressed_btn));
        }else{
            viewHolder.wishBtn.setBackground(mActivity.getResources().getDrawable(R.mipmap.wish_normal_btn));
        }

        //祝福点赞
        viewHolder.wishLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!DBUtil.getInstance(mActivity).getLikeWish(wish)){
                    like(viewHolder,wish,position);
                }
            }
        });

        //祝福点赞
        viewHolder.wishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!DBUtil.getInstance(mActivity).getLikeWish(wish)){
                    like(viewHolder,wish,position);
                }
            }
        });

        //宽 >= 高时 横向照片（3:4）
        int firstheight=(App.screenWidth -PicUtil.dip2px(mActivity,20))*3/4;
        //宽 < 高时 竖向照片 (8:7)
        int secondHeight=(App.screenWidth-PicUtil.dip2px(mActivity,20))*8/7;
        if(wish.getPhotoWidth()>=wish.getPhotoHeight()){
            viewHolder.photoView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,firstheight));
        }else{
            viewHolder.photoView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,secondHeight));
        }
        UniversalImageLoader.getIntance().displayImage(wish.getPhotoUrl(), viewHolder.photoView, UniversalImageLoader.getPhotorOptions(), UniversalImageLoader.getAnimateFirstDisplayListener());


        return convertView;
    }



    public EditText editText;

    public void like(final ViewHolder viewHolder,Wish wish,final int position){
        //判断是否已登录
        if(AVUser.getCurrentUser()==null){
            ActivityUtil.startActivity(mActivity, LoginActivity.class);
            return;
        }
        onLikedListener=new OnLikedListener() {
            @Override
            public void onComplete(boolean isComplete) {
                if(isComplete){
                    App.mWishList.get(position).setIsLike(true);
                    mData.get(position).setIsLike(true);
                }
            }
        };

        MyAlertView.alertView=new AlertView(null,null, "取消", null, new String[]{"祝愿"}, mActivity, AlertView.Style.Alert,new OnItemClickListener(viewHolder,wish,position));
        ViewGroup extView = (ViewGroup) LayoutInflater.from(mActivity).inflate(R.layout.love_wish_like_dialog,null);
        editText = (EditText) extView.findViewById(R.id.love_wish_like_dialog_edit);
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean focus) {
                //输入框出来则往上移动
                boolean isOpen = CommonUtil.isShowSoftInputView(mActivity);
                MyAlertView.alertView.setMarginBottom(isOpen && focus ? 80 : 0);
            }
        });
        MyAlertView.alertView.addExtView(extView);
        MyAlertView.alertView.show();
    }

    public OnLikedListener onLikedListener;
    public interface OnLikedListener{
        void onComplete(boolean isComplete);
    }

    public class OnItemClickListener implements com.bigkoo.alertview.OnItemClickListener{

        private ViewHolder viewHolder;
        private Wish wish;
        private int position;

        public OnItemClickListener(ViewHolder viewHolder,Wish wish,int position){
            this.viewHolder=viewHolder;
            this.wish=wish;
            this.position=position;
        }

        @Override
        public void onItemClick(final Object o, int position) {
            CommonUtil.closeSoftInputViewFromWindow(mActivity,editText,MyAlertView.alertView);
            //判断是否是拓展窗口View，而且点击的是非取消按钮
            if(o == MyAlertView.alertView && position != AlertView.CANCELPOSITION){
                String content=editText.getText().toString();
                if(content.isEmpty()){
                    return;
                }
                AVObject comment=new AVObject("WishComment");
                comment.put("content",content);
                comment.put("user",AVUser.getCurrentUser());
                comment.put("wish",AVObject.createWithoutData("Wish", wish.getObjectId()));
                //添加权限
                AVACL acl=new AVACL();
                acl.setPublicReadAccess(true);
                //设置评论仅发布者和评论者可写
                acl.setWriteAccess(AVUser.getCurrentUser(),true);
                acl.setWriteAccess(wish.getUser(),true);
                comment.setACL(acl);
                comment.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if(null==e){
                            viewHolder.wishCount.setText((wish.getLikeCount() + 1) + "");
                            viewHolder.wishBtn.setBackground(mActivity.getResources().getDrawable(R.mipmap.wish_pressed_btn));
                            final AVObject likes = AVObject.createWithoutData("Likes",wish.getLikesObjectId());
                            likes.setFetchWhenSave(true);
                            likes.increment("likeCount");
                            likes.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(AVException e) {
                                    if(e!=null)return;
                                    DBUtil.getInstance(mActivity).likeWish(wish);
                                    viewHolder.wishCount.setText(likes.get("likeCount")+"");
                                    if(onLikedListener!=null){
                                        onLikedListener.onComplete(true);
                                    }
                                }
                            });
                        }else {
                            if(onLikedListener!=null){
                                onLikedListener.onComplete(false);
                            }
                        }
                    }
                });
            }
        }
    }

}
